# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import re
import os
import zipfile
from configparser import ConfigParser
import proxys
import ua
from pyvirtualdisplay import Display

cf = ConfigParser()
cf.read("config.ini")

# Chrome代理模板插件(https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy)目录
CHROME_PROXY_HELPER_DIR = 'Chrome-proxy-helper'
# 存储自定义Chrome代理扩展文件的目录
CUSTOM_CHROME_PROXY_EXTENSIONS_DIR = 'chrome-proxy-extensions'

class Ctrip():
    _instance_lock = None

    def __init__(self):
        host = cf.get("Mysql-Database", "host")
        port = cf.get("Mysql-Database", "port")
        user = cf.get("Mysql-Database", "user")
        passwd = cf.get("Mysql-Database", "passwd")
        db = cf.get("Mysql-Database", "db")
        charset = cf.get("Mysql-Database", "charset")

        # self.conn = pymysql.connect(host=host, port=int(port), user=user, passwd=passwd, db=db, charset=charset)
        # self.cur = self.conn.cursor()
        self.proxy = proxys.get_proxy()
        self.ck = {}

    # 单列模式
    def __new__(cls, *args, **kwargs):  # 这三个参数是解释器自动添加的，这些参数实际上是给__init__方法用的。
        if Ctrip._instance_lock is None:  # 如果这个实例对象还是None
            Ctrip._instance_lock = object.__new__(cls)  # 调用父类的__new__方法来开辟内存
        return Ctrip._instance_lock

    def login(self, user, password,CRS_ID):
        # shutil.rmtree('./chrome-proxy-extensions')
        self.ck = {}
        try:
            while True:
                try:
                    # 使用Chrome代理扩展 get_chrome_proxy_extension
                    a = self.get_chrome_proxy_extension(proxy=self.proxy)
                    chrome_options = Options()
                    chrome_options.add_extension(a)
                    chrome_options.add_argument('--disable-gpu')
                    chrome_options.add_argument('log-level=3')

                    useragent = ua.get_ua()
                    print(useragent)
                    chrome_options.add_argument('user-agent=' + useragent)
                    # 禁止加载图片
                    prefs = {
                        'profile.default_content_setting_values': {
                            'images': 2,
                            # 'javascript': 2
                        }
                    }
                    chrome_options.add_experimental_option('prefs', prefs)
                    # 虚拟窗口====
                    display = Display(visible=0, size=(900, 800))
                    display.start()

                    driver = webdriver.Chrome(options=chrome_options)
                    # driver.maximize_window()
                    # 设置超时
                    driver.set_page_load_timeout(30)
                    driver.set_script_timeout(30)

                    url = 'http://ebooking.ctrip.com/ebkassembly/login.aspx'
                    driver.get(url)
                except Exception as err:
                    print(err)
                    try:
                        driver.quit()
                        display.stop()
                    except:
                        pass
                    self.proxy=proxys.get_proxy()
                    continue
                # 获取首页内容
                index_con = driver.page_source
                # 点击用户名输入框
                input_username = driver.find_element_by_id('userName')
                input_username.clear()  # 清除输入框
                time.sleep(0.1)
                # 输入账号
                for i in user:
                    input_username.send_keys(i)
                    time.sleep(0.1)
                input_password = driver.find_element_by_id('userPwd')
                input_password.clear()  # 清除输入框
                time.sleep(0.1)
                # 输入密码
                for i in password:
                    input_password.send_keys(i)
                    time.sleep(0.1)
                # 滑块存在
                if 'div class="slidebar-item" style="margin: 0px 0px 10px;" id="identifyCodeForUser1"' in index_con:
                    print('滑块存在')
                    self.delete_proxy(a)
                    self.proxy = proxys.get_proxy()
                    driver.quit()
                    display.stop()
                    return 0

                else:
                    # 点击登录
                    subbmit = driver.find_element_by_id('accSubmit')
                    subbmit.click()
                    time.sleep(3)
                    con = driver.page_source
                    if '用户名或密码错误' in con or 'Incorrect user name or password' in con:
                        print('用户名或密码错误')
                        driver.quit()
                        display.stop()
                        return 1

                    elif 'HotelName' in con:
                        print('登录成功')
                        # 获取cookie
                        self.cookies = driver.get_cookies()
                        driver.quit()
                        display.stop()
                        break

                    elif '请关注合作协议更新' in con:
                        print('请关注合作协议更新')
                        # 获取cookie
                        self.cookies = driver.get_cookies()
                        driver.quit()
                        display.stop()
                        break

                    else:
                        print('重试')
                        self.delete_proxy(a)
                        self.proxy=proxys.get_proxy()
                        driver.quit()
                        display.stop()
                        continue

        except Exception as err:
            if 'Message: unexpected alert open: {Alert text : 有携程网的【紧急】订单，立即点击“确定”前往处理}' in str(err):
                print('订单弹窗')
                # 获取cookie
                try:
                    self.cookies = driver.get_cookies()
                except:
                    driver.quit()
                    display.stop()
                    return 0
                driver.quit()
            else:
                print('未知错误')
                driver.quit()
                display.stop()
                return 0
        try:
            self.delete_proxy(a)
        except:
            pass
        try:
            for c in self.cookies:
                name = c['name']
                value = c['value']
                self.ck[name] = value
        except:
            try:
                driver.quit()
                display.stop()
            except:
                pass
            return 0

        return self.ck

    def delete_proxy(self,a):
        try:
            os.remove(a)
        except Exception as err:
            print(err)


    # Chrome代理扩展
    def get_chrome_proxy_extension(self, proxy):
        """获取一个Chrome代理扩展,里面配置有指定的代理(带用户名密码认证)
        proxy - 指定的代理,格式: username:password@ip:port
        """
        proxy = str(proxy).replace('http://', '')
        m = re.compile('([^:]+):([^\@]+)\@([\d\.]+):(\d+)').search(proxy)
        if m:
            # 提取代理的各项参数
            username = m.groups()[0]
            password = m.groups()[1]
            ip = m.groups()[2]
            port = m.groups()[3]
            # 创建一个定制Chrome代理扩展(zip文件)
            if not os.path.exists(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR):
                os.mkdir(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR)
            extension_file_path = os.path.join(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR,
                                               '{}.zip'.format(proxy.replace(':', '_')))
            if not os.path.exists(extension_file_path):
                # 扩展文件不存在，创建
                zf = zipfile.ZipFile(extension_file_path, mode='w')
                zf.write(os.path.join(CHROME_PROXY_HELPER_DIR, 'manifest.json'), 'manifest.json')
                # 替换模板中的代理参数
                background_content = open(os.path.join(CHROME_PROXY_HELPER_DIR, 'background.js')).read()
                background_content = background_content.replace('%proxy_host', ip)
                background_content = background_content.replace('%proxy_port', port)
                background_content = background_content.replace('%username', username)
                background_content = background_content.replace('%password', password)
                zf.writestr('background.js', background_content)
                zf.close()

            return extension_file_path
        else:
            raise Exception('Invalid proxy format. Should be username:password@ip:port')
